<template>
    <div ref="radioGroupRef" class="pe-radio-group" :id="id">
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { ref, provide, watch } from "vue"

const modelValue = defineModel<string | boolean | number>()

/**
 * @param size 单选框尺寸
 * @param disabled 是否禁用
 */
interface Props {
    size?: 'default' | 'large' | 'small',
    disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    size: "default",
    disabled: false
})

const emits = defineEmits(["change"])

watch(modelValue, newValue => {
    emits("change", newValue)
})

const radioGroupRef = ref<HTMLDivElement>()

// 获取随机id
const getId = (): string => {
    return 'xxx-xxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

const id = ref<string>(`pe-radio-${getId()}`)

// onMounted(() => {
//     const radios =
//         radioGroupRef.value!.querySelectorAll<HTMLInputElement>('[type=radio]')
//     radios.forEach(item => {
//         item.name = tempId
//     })
// })

const radioSize = ref<'default' | 'large' | 'small'>()
const radioDisabled = ref<boolean>(false)

watch(props, newProps => {
    radioSize.value = newProps.size
    radioDisabled.value = newProps.disabled
}, {immediate: true})

provide("pe-radio-value", modelValue)
provide("pe-radio-id", id)
provide("pe-radio-size", radioSize)
provide("pe-radio-disabled", radioDisabled)
</script>

<script lang="ts">
export default {
    name: "pe-radio-group"
}
</script>
